﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Red.CommUtils
{
    public static class ConsoleCommand
    {
        public static comm.Message CreateFromString(string command)
        {
            string[] tokens = command.Split(' ');

            string messageType = tokens[0];
            var message = Activator.CreateInstance("Red.CommProtocol", "comm." + messageType).Unwrap();

            for( int i=1; i<tokens.Count(); ++i )
            {
                string[] param = tokens[i].Split('=');
                string propertyName = param[0];
                string value = param[1];
                Type type = message.GetType();
                FieldInfo fieldInfo = type.GetField(propertyName);
                fieldInfo.SetValue(message, Convert.ChangeType(value, fieldInfo.FieldType));
            }

            return (comm.Message)message;
        }
    }
}
